package capaPresentacion;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.*;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;

public class RedirectedFrame extends JFrame {
	private static final long serialVersionUID = 1L;
    private JTextArea aTextArea;
    private JScrollPane areaScrollPane;
    private PrintStream aPrintStream;

   public RedirectedFrame(String n) {
       aPrintStream  = new PrintStream(new FilteredStream(new ByteArrayOutputStream()));
       
	   ///***INICIALIZAR FRAME***\\\
       setResizable(false);
	   setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
	   System.setOut(aPrintStream);
	   setTitle(n);
	   setSize(700,700);
	   getContentPane().setLayout(new BorderLayout());
	   ///***********************\\\
      
      ///***SCROLLPANEL***\\\
      aTextArea = new JTextArea();
      areaScrollPane = new JScrollPane(aTextArea);
      areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
      areaScrollPane.setWheelScrollingEnabled(true);
      areaScrollPane.setPreferredSize(new Dimension(600, 600));
      ///*****************\\\
      
      
      getContentPane().add(areaScrollPane, BorderLayout.NORTH);
      
      JButton btnMostrarMapa = new JButton("Mostrar Mapa");
      btnMostrarMapa.addMouseListener(new MouseAdapter() {
      	@Override
      	public void mouseClicked(MouseEvent arg0) {
      		Ventana.main(null);
      		
      	}
      });
      areaScrollPane.setColumnHeaderView(btnMostrarMapa);
      displayLog();
      addWindowListener
         (new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
               dispose();
               }
            }
         );
      }

   private class FilteredStream extends FilterOutputStream {
      public FilteredStream(OutputStream aStream) {
         super(aStream);
         }

        @Override
      public void write(byte b[]) throws IOException {
         String aString = new String(b);
         ((JTextArea) areaScrollPane.getComponent(0)).append(aString);
         }

        @Override
      public void write(byte b[], int off, int len) throws IOException {
         String aString = new String(b , off , len);
         aTextArea.append(aString);
         FileWriter aWriter = new FileWriter("error.log", true);
         aWriter.write(aString);
         aWriter.close();
         }
      }

   private void displayLog() {
      Dimension dim = getToolkit().getScreenSize();
      Rectangle abounds = getBounds();
      setLocation((dim.width - abounds.width) / 2,
         (dim.height - abounds.height) / 2);
      setVisible(true);
      requestFocus();
   }
   
   public void cambiarNombre(String n){
	  setTitle(n);
   }
}